<template>
  <div class="coupon-container">
    <button class="back-button" @click="goBack">
      <svg viewBox="0 0 24 24" width="24" height="24">
        <path fill="currentColor" d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z" />
      </svg>
    </button>

    <div class="coupon-card">
      <h1 class="coupon-title">{{ scopeData.couponName }}</h1>
      <p class="coupon-subtitle">随时领取，先到先得</p>

      <div class="coupon-content">
        <p class="coupon-desc">{{ scopeData.description }}</p>

        <div class="coupon-feature">
          <span class="feature-checkbox">✓</span>
          <span class="feature-text">有效期：{{ scopeData.validPeriod }}天</span>
        </div>

        <div class="coupon-feature">
          <span class="feature-checkbox">✓</span>
          <span class="feature-text">立即激活</span>
        </div>

        <button
            class="activate-btn"
            @click="activateCoupon"
            :disabled="isActivating || hasReceived"
        >
          {{ hasReceived ? '已领取' : isActivating ? '激活中...' : '立即激活' }}
        </button>

        <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
      </div>

      <p class="coupon-footer">
        激活后优惠券将存入您的账户，可在"我的优惠券"中查看
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { useExampleStore } from "@/stores/exampleStore.js";
import axios from "axios";
import { ElMessage } from 'element-plus'; // 使用Element Plus的消息组件

const router = useRouter();
const exampleStore = useExampleStore();
const scopeData = exampleStore.scopeData;
const schoolId = exampleStore.getSchool;

// 状态管理
const isActivating = ref(false);
const hasReceived = ref(false);
const errorMessage = ref("");
import { getToken } from '@/utils/auth'; // 导入获取令牌的工具函数
const token = getToken();
console.log(token)

onMounted(async () => {
  await checkCouponReceived();
});

const goBack = () => {
  router.back();
};

// 检查用户是否已领取过该校优惠券
const checkCouponReceived = async () => {
  try {
    const response = await axios.get(
        'http://localhost:8080/platform/coupons/check',
        {
          params: { schoolId },
          headers: {
            'Authorization': `Bearer ${token}`,
          }
        }
    );
    hasReceived.value = response.data.data?.hasReceived || false;
  } catch (error) {
    console.error('检查优惠券领取状态失败:', error);
    errorMessage.value = error.response?.data?.msg || "无法检查优惠券状态，请稍后再试";
    ElMessage.error(errorMessage.value); // 修改为ElMessage
  }
};

const activateCoupon = async () => {
  if (hasReceived.value) {
    errorMessage.value = "您已领取过该校的优惠券，每个学校限领一次";
    ElMessage.error(errorMessage.value); // 修改为ElMessage
    return;
  }

  isActivating.value = true;
  errorMessage.value = "";

  const requestData = {
    couponId: scopeData.couponId,
    schoolId: Number(schoolId)
  };


  try {
    const response = await axios.post(
        'http://localhost:8080/platform/coupons/activate',
        requestData,
        {
          headers: { 'Authorization': `Bearer ${token}` }// 添加令牌到请求头
        }
    );

    if (response.data.code === 200) {
      hasReceived.value = true;
      ElMessage.success('优惠券激活成功！'); // 修改为ElMessage
    } else {
      errorMessage.value = response.data.msg || "激活失败，请稍后再试";
      ElMessage.error(errorMessage.value); // 修改为ElMessage
    }
  } catch (error) {
    console.error('激活优惠券失败:', error);
    errorMessage.value = error.response?.data?.msg || "网络错误，请稍后再试";
    ElMessage.error(errorMessage.value); // 修改为ElMessage
  } finally {
    isActivating.value = false;
  }
};
</script>

<style scoped>
.coupon-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  background: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: all 0.2s ease;
}

.back-button:hover {
  background: #f5f5f5;
  transform: translateX(-2px);
}

.coupon-card {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 30px;
  text-align: center;
}

.coupon-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.coupon-subtitle {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

.coupon-content {
  margin: 25px 0;
}

.coupon-desc {
  font-size: 16px;
  color: #444;
  margin-bottom: 20px;
  line-height: 1.6;
}

.coupon-feature {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 15px;
}

.feature-checkbox {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border: 2px solid #4CAF50;
  border-radius: 4px;
  color: #4CAF50;
  font-weight: bold;
}

.feature-text {
  font-size: 15px;
  color: #555;
}

.activate-btn {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #4CAF50, #8BC34A);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.activate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.coupon-footer {
  font-size: 13px;
  color: #888;
  margin-top: 20px;
  line-height: 1.5;
}
</style>